package com.sskj.lib.mvchelper;

import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.MutableLiveData;

import com.shizhefei.mvc.RequestHandle;
import com.shizhefei.mvc.ResponseSender;
import com.shizhefei.task.IAsyncTask;
import com.sskj.common.util.RxSchedulersHelper;

import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

/**
 * 任意布局，展示各种状态界面，请求数据
 */
@SuppressWarnings("unchecked")
public class NormalDataSource<T> implements IAsyncTask<T> {
    private LifecycleOwner lifecycleOwner;
    private MutableLiveData tMutableLiveData;
    private ResponseSender sender;
    private OnLoadSource onLoadSource;

    public NormalDataSource(LifecycleOwner lifecycleOwner, OnLoadSource onLoadSource) {
        this.lifecycleOwner = lifecycleOwner;
        this.onLoadSource = onLoadSource;
        tMutableLiveData = new MutableLiveData<>();
        tMutableLiveData.observe(lifecycleOwner, t -> sender.sendData(t));
    }

    public interface OnLoadSource<T> {
        Flowable<T> loadData();
    }

    @Override
    public RequestHandle execute(ResponseSender sender) throws Exception {

        this.sender = sender;
        Disposable subscribe = onLoadSource.loadData()
                .compose(RxSchedulersHelper.transformer())
                .subscribe(o -> {
                    if (lifecycleOwner != null) {
                        tMutableLiveData.postValue(o);
                    } else {
                        sender.sendData(o);
                    }
                }, throwable -> sender.sendError(new Exception((Throwable) throwable)));
        return null;
    }
}
